package com.sinog.biz.service.xml.impl;

import com.alibaba.fastjson.JSON;
import com.sinog.biz.config.ProvinceCodes3Config;
import com.sinog.biz.mapper.havexml.AbPrisonerMapper;
import com.sinog.biz.mapper.havexml.HnInterfaceOppositeMapper;
import com.sinog.biz.mapper.havexml.PrisonerFxMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainMapper;
import com.sinog.biz.mapper.havexml.PrisonerSrMapper;
import com.sinog.biz.mapper.havexml.PrisonerXjxxMapper;
import com.sinog.biz.mapper.havexml.PrisonerZnMapper;
import com.sinog.biz.mapper.havexml.SystemCodeMapper;
import com.sinog.biz.mapper.havexml.UploadAppendixFileMapper;
import com.sinog.biz.mapper.havexml.VerificationMapper;
import com.sinog.biz.mapper.havexml.XjReceiptDataVoMapper;
import com.sinog.biz.mapper.havexml.XjReceiptMapper;
import com.sinog.biz.mapper.havexml.XxblMapper;
import com.sinog.biz.mapper.havexml.other.UserLoginDetailsMapper;
import com.sinog.biz.service.api.DataTransmissionService;
import com.sinog.biz.service.business.PrisonerSrBatchService;
import com.sinog.biz.service.business.PrisonerZnBatchService;
import com.sinog.biz.service.xml.InterfaceDockingService;
import com.sinog.biz.util.BusinessUtils;
import com.sinog.biz.util.CheckUtil;
import com.sinog.biz.util.IdGen;
import com.sinog.biz.util.smlib.Sm4;
import com.sinog.core.domain.PrisaveTemp;
import com.sinog.core.domain.PrisonerCjpg;
import com.sinog.core.domain.PrisonerFx;
import com.sinog.core.domain.PrisonerHc;
import com.sinog.core.domain.PrisonerJxjs;
import com.sinog.core.domain.PrisonerMain;
import com.sinog.core.domain.PrisonerSr;
import com.sinog.core.domain.PrisonerXjxx;
import com.sinog.core.domain.PrisonerZn;
import com.sinog.core.domain.UserInterFaceEntity;
import com.sinog.core.domain.XjReceipt;
import com.sinog.core.domain.xml.HnInterfaceOpposite;
import com.sinog.core.domain.xml.HnInterfaceOppositeLog;
import com.sinog.core.model.UploadAppendixFile;
import com.sinog.core.model.XjReceiptDataVo;
import com.sinog.core.model.xml.HnAjxxVo;
import com.sinog.core.model.xml.HnMessageVo;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.StrUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Dictionary;
import com.sinog.core.utilbean.HnStyleReturnCode;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 湖南个性化对接 - InterfaceDockingServiceImpl
 * @author wangxj
 * @date 2022/6/27 下午3:04
 */
@Slf4j
@Service
public class InterfaceDockingServiceImpl implements InterfaceDockingService {

    /**
     * 初始化字典表
     */
    private static final Dictionary DICTIONARY = Dictionary.getSingleton();
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SystemCodeMapper systemCodeMapper;
    @Resource
    private PrisonerMainMapper prisonerMainMapper;
    @Resource
    private PrisonerFxMapper prisonerFxMapper;
    @Resource
    private CheckUtil checkUtil;
    @Resource
    private UserLoginDetailsMapper userLoginDetailsMapper;
    @Resource
    private HnInterfaceOppositeMapper hnInterfaceOppositeMapper;
    @Resource
    private PrisonerSrMapper prisonerSrMapper;
    @Resource
    private PrisonerZnMapper prisonerZnMapper;
    @Resource
    private XxblMapper xxblMapper;
    @Resource
    private PrisonerXjxxMapper prisonerXjxxMapper;
    @Resource
    private VerificationMapper verificationMapper;
    @Resource
    private PrisonerZnBatchService prisonerZnBatchService;
    @Resource
    private PrisonerSrBatchService prisonerSrBatchService;
    @Resource
    private DataTransmissionService dataTransmissionService;
    @Resource
    private AbPrisonerMapper abPrisonerMapper;
    @Resource
    private XjReceiptMapper xjReceiptMapper;
    @Resource
    private XjReceiptDataVoMapper xjReceiptDataVoMapper;
    @Resource
    private UploadAppendixFileMapper uploadAppendixFileMapper;
    @Resource
    private ProvinceCodes3Config provinceCodes3Config;

    /**
     * 保存预安置人员 (1、基本信息 2、服刑信息 3、配偶、父母，社会关系 4、子女信息)
     * 保存核查信息 (5、核查信息)
     * @param paramMap 接口传递信息
     * @return Result 返回结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result automaticVerification(Map<String,List<Map<String,String>>> paramMap) {
        String processType = paramMap.get("processType").get(0).get("processType");
        HnMessageVo hnMessage = JsonUtil.toBean(JsonUtil.toText(paramMap.get("MESSAGE").get(0)),HnMessageVo.class);
        // 1、定义返回结果
        Result result = new Result();
        Result result2 = new Result();
        Result result1 = checkUtil.checkParams(paramMap);
        if(!ReturnCode.SUCCESS.code().equals(result1.getCode())) {
            return Result.failure(result1.getCode(),(String)result1.getData(),getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
        }
        try {
            result2 = checkUtil.asscessParams(paramMap,processType);
        } catch(Exception e) {
            e.printStackTrace();
        }
        PrisonerMain prisonerMain = new PrisonerMain();
        PrisonerFx prisonerFx = new PrisonerFx();
        List<PrisonerSr> prisonerSrs = new ArrayList<>();
        List<PrisonerZn> prisonerZns = new ArrayList<>();
        PrisonerHc prisonerHc = new PrisonerHc();
        PrisaveTemp prisaveTemp = new PrisaveTemp();
        HnAjxxVo hnAjxx = new HnAjxxVo();
        // 获取流程节点,跨部门编号等信息
        HnInterfaceOpposite hnInterfaceOpposite = new HnInterfaceOpposite();
        // 校验信息落幕
        Result check = check(JsonUtil.toText(result2.getData()),hnMessage);
        if(!ReturnCode.SUCCESS.code().equals(check.getCode())) {
            Map<String,String> resultMap = (HashMap<String,String>)check.getData();
            return Result.failure(check.getCode(),check.getMessage(),resultMap);
        }
        // 获取校验后的参数信息
        try {
            {
                List<Object> checkData = (List<Object>)check.getData();
                for(Object next : checkData) {
                    if(next instanceof PrisonerMain) {
                        prisonerMain = (PrisonerMain)next;
                    }
                    if(next instanceof PrisonerFx) {
                        prisonerFx = (PrisonerFx)next;
                    }
                    if(next instanceof List) {
                        for(Object next1 : (List)next) {
                            if(next1 instanceof PrisonerZn) {
                                prisonerZns.add((PrisonerZn)next1);
                            }
                            if(next1 instanceof PrisonerSr) {
                                prisonerSrs.add((PrisonerSr)next1);
                            }
                        }
                    }
                    if(next instanceof PrisonerHc) {
                        prisonerHc = (PrisonerHc)next;
                    }
                    if(next instanceof HnMessageVo) {
                        hnMessage = (HnMessageVo)next;
                    }
                    if(next instanceof HnAjxxVo) {
                        hnAjxx = (HnAjxxVo)next;
                    }
                }
            }
            // 获取接口对接用户
            String fsdwCode = hnMessage.getFsdwCode();
            UserInterFaceEntity user = userLoginDetailsMapper.getInfoByDepartId(fsdwCode);
            if(null == user) {
                // 找不到用户
                return Result.failure(HnStyleReturnCode.NOT_FIND_USER,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
            }
            // 组装基本数据
            assembled(user,prisonerMain,prisonerFx,prisonerSrs,prisonerZns,prisonerHc,prisaveTemp,hnInterfaceOpposite,hnMessage,hnAjxx);
            // 生成犯罪编号
            result = makePriNum(user,prisonerMain,prisonerFx,prisonerSrs,prisonerZns,prisonerHc,prisaveTemp,hnInterfaceOpposite,hnMessage);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据服刑人员编号查找是否为湖南个性化对接数据
     * @param prinum 服刑人员编号
     * @return Result
     */
    @Override
    public Result getHnInterfaceOppositeByPriNum(String prinum) {
        int count = hnInterfaceOppositeMapper.selectCountByPriNum(prinum);
        if(count > 0) {
            return Result.success(count);
        }
        return Result.failure(Constants.Number.NUM_ZERO);
    }

    /**
     * 返回XML信息,跨部门办案号,流程实例编号
     * @param hnMessage HnMessageVo
     * @param type 1:接收成功,2:接收失败
     * @return Object
     */
    private <T extends Object> T getResultMap(HnMessageVo hnMessage,String type) {
        HashMap<String,String> resultMap = new HashMap<>(16);
        resultMap.put("KBMBAH",hnMessage.getKbmbah());
        resultMap.put("RWH",hnMessage.getRwh());
        resultMap.put("LCSLBH",hnMessage.getLcslbh());
        resultMap.put("PROCESS_NO",Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_A);
        resultMap.put("AJMC",hnMessage.getAjmc());
        resultMap.put("LCLX_CODE",Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO);
        resultMap.put("LCLX_NAME",Constants.HnInterfaceDocking.ZHIXINGJIESHOU);
        resultMap.put("JSDWLX","4B");
        Map<String,Map<String,String>> tsmessage = provinceCodes3Config.getTSMESSAGE();
        Map<String,String> fsdwCodes = tsmessage.get("FSDW_CODE");
        for(Map.Entry<String,String> fsdw : fsdwCodes.entrySet()) {
            if(fsdw.getKey().indexOf(hnMessage.getFsdwCode())>=0 ||
                    fsdw.getValue().indexOf(hnMessage.getFsdwCode())>=0 ){
                resultMap.put("JSDW_CODE",fsdw.getKey());
            }
        }
        resultMap.put("JSDW_NAME",hnMessage.getFsdwName());
        resultMap.put("JSDWSZD",hnMessage.getFsdwszd());
        resultMap.put("JSDWXZQ_CODE",hnMessage.getJsdwxzqCode());
        resultMap.put("JSDWXZQ_NAME",hnMessage.getJsdwxzqName());
        resultMap.put("FSDWLX","5D");
        resultMap.put("FSDW_CODE",hnMessage.getJsdwCode());
        resultMap.put("FSDW_NAME",hnMessage.getJsdwName());
        resultMap.put("FSDWSZD",hnMessage.getJsdwszd());
        resultMap.put("FSDWXZQ_CODE",hnMessage.getFsdwxzqCode());
        resultMap.put("FSDWXZQ_NAME",hnMessage.getFsdwxzqName());
        resultMap.put("FS_TIME",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        resultMap.put("JGZT",Constants.NumberStr.NUM_STR_ONE.equals(type) ? Constants.HnInterfaceDocking.NUM_STR_TWO_ZERO_TWO : Constants.HnInterfaceDocking.NUM_STR_FOUR_ZERO_TWO);
        resultMap.put("ZTMS",Constants.NumberStr.NUM_STR_ONE.equals(type) ? "接收成功" : "接收失败");
        resultMap.put("YSR","");
        resultMap.put("YSRDH","");
        resultMap.put("CBR","");
        resultMap.put("CBRDH","");
        resultMap.put("ZIPNAME",hnMessage.getZipName());
        return (T)resultMap;
    }

    /**
     * 生成犯罪编号
     * @param user 接口调用用户
     * @param prisonerMain 基本信息
     * @param prisonerFx 服刑信息
     * @param prisonerSrs 社会关系信息
     * @param prisonerZns 未成年子女信息
     * @param prisonerHc 发起核查信息
     * @param prisaveTemp 状态表
     * @param hnInterfaceOpposite hnInterfaceOpposite
     * @param hnMessage hnMessage
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class)
    public Result makePriNum(UserInterFaceEntity user,PrisonerMain prisonerMain,PrisonerFx prisonerFx,List<PrisonerSr> prisonerSrs,List<PrisonerZn> prisonerZns,PrisonerHc prisonerHc,PrisaveTemp prisaveTemp,HnInterfaceOpposite hnInterfaceOpposite,HnMessageVo hnMessage) {
        // 1、定义生成的犯罪编号
        String priNum;
        // 跨部门人员编号
        String kbmrybh = hnInterfaceOpposite.getKbmrybh();
        HnInterfaceOpposite hnInterfaceOpposite1 = hnInterfaceOppositeMapper.selectHnByKbmrybh(kbmrybh,null,null);
        if(null != hnInterfaceOpposite1) {
            priNum = hnInterfaceOpposite1.getPriNum();
        } else {
            priNum = BusinessUtils.makePriNum(prisonerMainMapper,stringRedisTemplate,user.getDepartid(),user.getLevel());
            if(Constants.StrFinalValue.ERROR.equals(priNum)){
                return Result.failure(ReturnCode.FAILURE,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
            }
        }
        // 9、调用入库方法
        return saveT(prisonerMain,prisonerFx,prisonerSrs,prisonerZns,prisaveTemp,prisonerHc,priNum,hnInterfaceOpposite,hnMessage,user);
    }

    /**
     * 保存信息入库
     * @param prisonerMain 基本信息
     * @param prisonerFx 服刑信息
     * @param prisonerSrs 社会关系信息
     * @param prisonerZns 未成年子女信息
     * @param prisaveTemp 状态表信息
     * @param prisonerHc 发起核查信息
     * @param priNum 犯罪编号
     * @param hnInterfaceOpposite 湖南个性化对接存储记录表
     * @param hnMessage hnMessage
     * @param user user
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class)
    public Result saveT(PrisonerMain prisonerMain,PrisonerFx prisonerFx,List<PrisonerSr> prisonerSrs,List<PrisonerZn> prisonerZns,PrisaveTemp prisaveTemp,PrisonerHc prisonerHc,String priNum,HnInterfaceOpposite hnInterfaceOpposite,HnMessageVo hnMessage,UserInterFaceEntity user) {
        // 1、定义入库开始时间

        long start = System.currentTimeMillis();
        Date date = prisonerMain.getUpdateTime();
        try {
            // 跨部门人员编号
            String kbmrybh = hnInterfaceOpposite.getKbmrybh();
            HnInterfaceOpposite hnInterfaceOpposite1 = hnInterfaceOppositeMapper.selectHnByKbmrybh(kbmrybh,Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_A,Constants.NumberStr.NUM_STR_ZERO);
            if(null != hnInterfaceOpposite1) {
                Map<String,Object> abPrisonersResultVo = abPrisonerMapper.getBaseInfoByPriNum(priNum);
                if(MapUtils.isNotEmpty(abPrisonersResultVo)){
                    return Result.failure(HnStyleReturnCode.ZFBH_AZBJ_STATUS,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                }
                // 废除不需要的流程节点(因为hn_interface_opposite表中会有多条对接记录,如果hnInterfaceOpposite1不为空,则需要将之前流程节点的赋予废除标志位)
                hnInterfaceOppositeMapper.updateFlagByKbmrybh(kbmrybh,Constants.NumberStr.NUM_STR_ONE,Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_A);
                // 获取流程编号
                String processType = hnInterfaceOpposite1.getProcessType();
                HnInterfaceOppositeLog hnInterfaceOppositeLog = new HnInterfaceOppositeLog();
                hnInterfaceOppositeLog.setId(IdGen.strid());
                hnInterfaceOppositeLog.setPriNum(priNum);
                hnInterfaceOppositeLog.setCreateTime(date);
                if(Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_A.equals(processType)) {
                    List<Object> xjReceiptDatas = new ArrayList<>();
                    // 将基本信息,服刑信息,社会关系,未成年子女信息,核查信息迁移至湖南接口备份表
                    HashMap<String,Object> verificationInfo = getVerificationInfo(priNum);
                    HashMap<String,Object> bridgingInfo = getBridgingInfo(priNum);
                    verificationInfo.putAll(bridgingInfo);
                    // 获取衔接信息
                    PrisonerXjxx prisonerXjxx = prisonerXjxxMapper.getXjxxByPriNum(priNum);
                    // 司法所完成衔接后进入安置帮教管理,需将abPrisoners保存到接口备份表
                    Map<String,Object> abPrisoners = abPrisonerMapper.getBaseInfoByPriNum(priNum);
                    if(null != abPrisoners && abPrisoners.size() > 0) {
                        verificationInfo.put("abPrisoners",abPrisoners);
                    }
                    // 获取回执信息
                    List<XjReceipt> xjReceipts = xjReceiptMapper.selectXjReceiveByPriNum(priNum);
                    for(XjReceipt xjReceipt : xjReceipts) {
                        List<XjReceiptDataVo> xjReceiptDataVos = xjReceiptDataVoMapper.selectXjReceiveMessagesBySessionId(xjReceipt.getXjid());
                        xjReceiptDatas.add(xjReceiptDataVos);
                        xjReceiptDataVoMapper.deleteBySessionId(xjReceipt.getXjid());
                    }
                    verificationInfo.put("PrisoonerXjxx",prisonerXjxx);
                    verificationInfo.put("xjReceipts",xjReceipts);
                    verificationInfo.put("xjReceiptDatas",xjReceiptDatas);
                    hnInterfaceOppositeLog.setData(JsonUtil.toText(verificationInfo));
                    hnInterfaceOppositeLog.insert();
                    // 删除职业技能和减刑假释,出监评估,衔接信息,安置帮教信息
                    xxblMapper.deleteJxjsByPriNum(priNum);
                    prisonerFxMapper.deleteCjpgByPriNum(priNum);
                    prisonerXjxxMapper.deleteByPriNum(priNum);
                    xjReceiptMapper.deleteByPriNum(priNum);
                    // 衔接证据
                    UploadAppendixFile uploadAppendixFile = new UploadAppendixFile();
                    uploadAppendixFile.setPriNum(priNum);
                    uploadAppendixFile.setTaskId(Constants.NumberStr.NUM_STR_TEN);
                    uploadAppendixFileMapper.removeAppendixFilByTaskId(uploadAppendixFile);
                }
            }
            // 2、为主表、多媒体表、服刑表、社会关系表、子女表、核查表、状态表 设置犯罪编号
            prisonerMain.setPriNum(priNum);
            prisonerFx.setPriNum(priNum);
            for(PrisonerSr prisonerSr : prisonerSrs) {
                prisonerSr.setPriNum(priNum);
            }
            for(PrisonerZn prisonerZn : prisonerZns) {
                prisonerZn.setPriNum(priNum);
            }
            prisonerHc.setPriNum(priNum);
            prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
            prisaveTemp.setPriNum(priNum);
            hnInterfaceOpposite.setPriNum(priNum);
            if(null != prisaveTemp.getFxFlag() && null != prisaveTemp.getMainFlag()) {
                if(Constants.Number.NUM_TWO == prisaveTemp.getFxFlag() + prisaveTemp.getMainFlag()) {
                    prisonerMain.setState(Constants.NumberStr.NUM_STR_TWO);
                }
            }
            // 3、入库主表
            if(!prisonerMain.insertOrUpdate()) {
                log.error("主表信息保存失败！");
                throw new RuntimeException("主表信息保存失败");
            }
            // 4、入库服刑表
            if(!prisonerFx.insertOrUpdate()) {
                log.error("服刑信息保存失败！");
                throw new RuntimeException("服刑信息保存失败");
            }
            // 5、入库社会关系表
            Map<String,Object> columnMap = new HashMap<>(16);
            columnMap.put("pri_Num",priNum);
            prisonerSrMapper.deleteByMap(columnMap);
            if(!prisonerSrBatchService.saveBatch(prisonerSrs)) {
                log.error("社会关系信息保存失败！");
                throw new RuntimeException("社会关系信息保存失败");
            }
            prisonerZnMapper.deleteByMap(columnMap);
            // 6、入库子女表
            if(!prisonerZnBatchService.saveBatch(prisonerZns)) {
                log.error("子女表保存失败！");
                throw new RuntimeException("子女表保存失败");
            }
            // 7、入库状态表
            if(!prisaveTemp.insertOrUpdate()) {
                log.error("状态表保存失败！");
                throw new RuntimeException("状态表保存失败");
            }
            // 8、入库核查信息表
            if(!prisonerHc.insertOrUpdate()) {
                log.error("状态表保存失败！");
                throw new RuntimeException("状态表保存失败");
            }
            // 9、入库对接存储记录表
            if(!hnInterfaceOpposite.insert()) {
                log.error("入库对接存储记录表失败");
                throw new RuntimeException("入库对接存储记录表失败");
            }
        } catch(RuntimeException e) {
            log.error("发生异常：",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failure(ReturnCode.FAILURE,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
        }
        // log.info("预安置人员信息录入【入库耗时】:{} ms",System.currentTimeMillis() - start);
        return Result.success(getResultMap(hnMessage,Constants.NumberStr.NUM_STR_ONE));
    }

    /**
     * 组装基本数据
     * @param user 调用接口用户信息
     * @param prisonerMain 基本信息
     * @param prisonerFx 服刑信息
     * @param prisonerSrs 社会关系信息
     * @param prisonerZns 未成年子女信息
     * @param prisonerHc 发起核查信息
     * @param prisaveTemp 状态表信息
     * @param hnMessage hnMessage
     * @param hnInterfaceOpposite hnInterfaceOpposite
     * @param hnAjxx hnAjxx
     */
    private void assembled(UserInterFaceEntity user,PrisonerMain prisonerMain,PrisonerFx prisonerFx,List<PrisonerSr> prisonerSrs,List<PrisonerZn> prisonerZns,PrisonerHc prisonerHc,PrisaveTemp prisaveTemp,HnInterfaceOpposite hnInterfaceOpposite,HnMessageVo hnMessage,HnAjxxVo hnAjxx) {
        Date date = new Date();
        // 取出监狱部门ID
        String departId = user.getDepartid();
        prisaveTemp.setId(IdGen.strid());
        prisaveTemp.setCreateUser(user.getAccount());
        prisaveTemp.setCreateTime(date);
        prisaveTemp.setUpdateUser(user.getAccount());
        prisaveTemp.setUpdateTime(date);
        prisonerMain.setId(IdGen.strid());
        prisonerMain.setAdduserid(departId);
        if(null == prisonerMain.getUsedName() || "".equals(prisonerMain.getUsedName())) {
            prisonerMain.setUsedName("无");
        }
        if(null == prisonerMain.getIdNum() || "".equals(prisonerMain.getIdNum())) {
            prisonerMain.setIdNum(Sm4.encryptEcb("无"));
        } else {
            prisonerMain.setIdNum(Sm4.encryptEcb(prisonerMain.getIdNum()));
        }
        prisonerMain.setAddusername(user.getUsername());
        prisonerMain.setPtype(user.getLevel());
        prisonerMain.setPrisonFather(user.getOrgid());
        prisonerMain.setPdanwei(user.getDepartid());
        prisonerMain.setPdanweiName(user.getDepartName());
        prisonerMain.setFlag(Constants.NumberStr.NUM_STR_ZERO);
        prisonerMain.setCreateUser(user.getAccount());
        prisonerMain.setCreateTime(date);
        prisonerMain.setUpdateUser(user.getAccount());
        prisonerMain.setUpdateTime(date);
        // 湖南社矫对接独立pstate
        prisonerMain.setPstate(Constants.InputEspecially.INPUT_KSS_HN_STYLE);
        if(!StringUtils.isEmpty(prisonerMain.getNativepro())) {
            String nativeProName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getNativepro());
            nativeProName = StringUtils.isEmpty(nativeProName) ? systemCodeMapper.getNameByCode(prisonerMain.getNativepro()) : nativeProName;
            prisonerMain.setNativeproName(nativeProName);
        } else {
            prisonerMain.setNativeproName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getNativecity())) {
            String nativeCityName = (String)stringRedisTemplate.opsForHash()
                                                               .get("areaCode",prisonerMain.getNativecity());
            nativeCityName = StringUtils.isEmpty(nativeCityName) ? systemCodeMapper.getNameByCode(prisonerMain.getNativecity()) : nativeCityName;
            prisonerMain.setNativecityName(nativeCityName);
        } else {
            prisonerMain.setNativecityName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getNativecou())) {
            String nativeCouName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getNativecou());
            nativeCouName = StringUtils.isEmpty(nativeCouName) ? systemCodeMapper.getNameByCode(prisonerMain.getNativecou()) : nativeCouName;
            prisonerMain.setNativecouName(nativeCouName);
        } else {
            prisonerMain.setNativecouName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getNativevill())) {
            String nativeVillName = (String)stringRedisTemplate.opsForHash()
                                                               .get("areaCode",prisonerMain.getNativevill());
            nativeVillName = StringUtils.isEmpty(nativeVillName) ? systemCodeMapper.getNameByCode(prisonerMain.getNativevill()) : nativeVillName;
            prisonerMain.setNativevillName(nativeVillName);
        } else {
            prisonerMain.setNativevillName("");
        }
        // 查不清人员
        if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getHjType())) {
            if(!StringUtils.isEmpty(prisonerMain.getInvestigatePro())) {
                String investigateProName = (String)stringRedisTemplate.opsForHash()
                                                                       .get("areaCode",prisonerMain.getInvestigatePro());
                investigateProName = StringUtils.isEmpty(investigateProName) ? systemCodeMapper.getNameByCode(prisonerMain.getInvestigatePro()) : investigateProName;
                prisonerMain.setInvestigateProName(investigateProName);
            } else {
                prisonerMain.setInvestigateProName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateCity())) {
                String investigateCityName = (String)stringRedisTemplate.opsForHash()
                                                                        .get("areaCode",prisonerMain.getInvestigateCity());
                investigateCityName = StringUtils.isEmpty(investigateCityName) ? systemCodeMapper.getNameByCode(prisonerMain.getInvestigateCity()) : investigateCityName;
                prisonerMain.setInvestigateCityName(investigateCityName);
            } else {
                prisonerMain.setInvestigateCityName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateCou())) {
                String investigateCouName = (String)stringRedisTemplate.opsForHash()
                                                                       .get("areaCode",prisonerMain.getInvestigateCou());
                investigateCouName = StringUtils.isEmpty(investigateCouName) ? systemCodeMapper.getNameByCode(prisonerMain.getInvestigateCou()) : investigateCouName;
                prisonerMain.setInvestigateCouName(investigateCouName);
            } else {
                prisonerMain.setInvestigateCouName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String investigateVillName = (String)stringRedisTemplate.opsForHash()
                                                                        .get("areaCode",prisonerMain.getInvestigateVill());
                investigateVillName = StringUtils.isEmpty(investigateVillName) ? systemCodeMapper.getNameByCode(prisonerMain.getInvestigateVill()) : investigateVillName;
                prisonerMain.setInvestigateVillName(investigateVillName);
            } else {
                prisonerMain.setInvestigateVillName("");
            }
        }
        // 非大陆户籍
        if(StrUtil.containsEquals(prisonerMain.getPriAddr(),DICTIONARY.getfdlpriaddr())) {
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String arrestProName = (String)stringRedisTemplate.opsForHash()
                                                                  .get("areaCode",prisonerMain.getArrestpro());
                arrestProName = StringUtils.isEmpty(arrestProName) ? systemCodeMapper.getNameByCode(prisonerMain.getArrestpro()) : arrestProName;
                prisonerMain.setArrestproName(arrestProName);
            } else {
                prisonerMain.setArrestproName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String arrestCityName = (String)stringRedisTemplate.opsForHash()
                                                                   .get("areaCode",prisonerMain.getArrestcity());
                arrestCityName = StringUtils.isEmpty(arrestCityName) ? systemCodeMapper.getNameByCode(prisonerMain.getArrestcity()) : arrestCityName;
                prisonerMain.setArrestcityName(arrestCityName);
            } else {
                prisonerMain.setArrestcityName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String arrestCouName = (String)stringRedisTemplate.opsForHash()
                                                                  .get("areaCode",prisonerMain.getArrestcou());
                arrestCouName = StringUtils.isEmpty(arrestCouName) ? systemCodeMapper.getNameByCode(prisonerMain.getArrestcou()) : arrestCouName;
                prisonerMain.setArrestcouName(arrestCouName);
            } else {
                prisonerMain.setArrestcouName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String arrestVillName = (String)stringRedisTemplate.opsForHash()
                                                                   .get("areaCode",prisonerMain.getArrestvill());
                arrestVillName = StringUtils.isEmpty(arrestVillName) ? systemCodeMapper.getNameByCode(prisonerMain.getArrestvill()) : arrestVillName;
                prisonerMain.setArrestvillName(arrestVillName);
            } else {
                prisonerMain.setArrestvillName("");
            }
        }
        // 若居住省市县街道编码不为空,则根据redis中行政区划数据获取对应的中文
        if(!StringUtils.isEmpty(prisonerMain.getPlacepro())) {
            String placeProName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getPlacepro());
            placeProName = StringUtils.isEmpty(placeProName) ? systemCodeMapper.getNameByCode(prisonerMain.getPlacepro()) : placeProName;
            prisonerMain.setPlaceproName(placeProName);
        } else {
            prisonerMain.setPlaceproName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getPlacecity())) {
            String placeCityName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getPlacecity());
            placeCityName = StringUtils.isEmpty(placeCityName) ? systemCodeMapper.getNameByCode(prisonerMain.getPlacecity()) : placeCityName;
            prisonerMain.setPlacecityName(placeCityName);
        } else {
            prisonerMain.setPlacecityName("");
        }
        if(null != prisonerMain.getPlacecou()) {
            String placeCouName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getPlacecou());
            placeCouName = StringUtils.isEmpty(placeCouName) ? systemCodeMapper.getNameByCode(prisonerMain.getPlacecou()) : placeCouName;
            prisonerMain.setPlacecouName(placeCouName);
        } else {
            prisonerMain.setPlacecouName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getPlacevill())) {
            String placevillName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getPlacevill());
            placevillName = StringUtils.isEmpty(placevillName) ? systemCodeMapper.getNameByCode(prisonerMain.getPlacevill()) : placevillName;
            prisonerMain.setPlacevillName(placevillName);
        } else {
            prisonerMain.setPlacevillName("");
        }
        prisonerMain.setDelFlag(Constants.NumberStr.NUM_STR_ZERO);
        boolean mainFlag = false;
        boolean fxFlag = false;
        if(StringUtils.isNotEmpty(prisonerMain.getPName()) && StringUtils.isNotEmpty(prisonerMain.getSex())
                && StringUtils.isNotEmpty(prisonerMain.getNationality()) && StringUtils.isNotEmpty(prisonerMain.getIdType())
                && null != prisonerMain.getAddtime() && StringUtils.isNotEmpty(prisonerMain.getEducation()) && StringUtils.isNotEmpty(prisonerMain.getPriAddr())) {
            if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getHjType())) {
                //如果户籍为查不清人员
                if(StringUtils.isNotEmpty(prisonerMain.getInvestigatePro()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateCity()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateCou()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateVill()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateNum())) {
                    prisaveTemp.setMainFlag(Constants.Number.NUM_ONE);
                    mainFlag = true;
                }
            } else if(Constants.NumberStr.NUM_STR_ZERO_FOUR.equals(prisonerMain.getPriAddr())){
                //如果户籍为完整并且非大陆
                if(StringUtils.isNotEmpty(prisonerMain.getArrestpro()) && StringUtils.isNotEmpty(prisonerMain.getArrestcity()) && StringUtils.isNotEmpty(prisonerMain.getArrestcou()) && StringUtils.isNotEmpty(prisonerMain.getArrestvill()) && StringUtils.isNotEmpty(prisonerMain.getArrestnum())) {
                    prisaveTemp.setMainFlag(Constants.Number.NUM_ONE);
                    mainFlag = true;
                }
            } else {
                //如果户籍为完整,湖南看守所无法提供户籍为类型
                if(StringUtils.isNotEmpty(prisonerMain.getNativepro()) && StringUtils.isNotEmpty(prisonerMain.getNativecity()) && StringUtils.isNotEmpty(prisonerMain.getNativecou()) && StringUtils.isNotEmpty(prisonerMain.getNativenum())) {
                    prisaveTemp.setMainFlag(Constants.Number.NUM_ONE);
                    mainFlag = true;
                }
            }
        }
        prisonerFx.setId(IdGen.strid());
        prisonerFx.setAdduserid(departId);
        prisonerFx.setCreateUser(user.getAccount());
        prisonerFx.setCreateTime(date);
        prisonerFx.setUpdateUser(user.getAccount());
        prisonerFx.setUpdateTime(date);
        if(StringUtils.isNotEmpty(prisonerFx.getCritype()) && StringUtils.isNotEmpty(prisonerFx.getPritime())
                && StringUtils.isNotEmpty(prisonerFx.getArrJg()) && StringUtils.isNotEmpty(prisonerFx.getPrecri()) && StringUtils.isNotEmpty(prisonerFx.getCanji()) && null != prisonerFx.getPriBegin() && null != prisonerFx.getPriStop() && StringUtils.isNotEmpty(prisonerFx.getAddpenalty()) && StringUtils.isNotEmpty(prisonerFx.getAftype()) && StringUtils.isNotEmpty(prisonerFx.getBqzy())) {
            prisaveTemp.setFxFlag(Constants.Number.NUM_ONE);
            fxFlag = true;
        }
        if(mainFlag && fxFlag) {
            prisaveTemp.setSrFlag(Constants.Number.NUM_ONE);
            prisaveTemp.setZzFlag(Constants.Number.NUM_ONE);
        }
        // 3.4、封装社会关系表
        for(PrisonerSr prisonerSr : prisonerSrs) {
            prisonerSr.setId(IdGen.strid());
            prisonerSr.setAdduserid(departId);
            prisonerSr.setCreateUser(user.getAccount());
            prisonerSr.setCreateTime(date);
            prisonerSr.setUpdateUser(user.getAccount());
            prisonerSr.setUpdateTime(date);
            if(!StringUtils.isEmpty(prisonerSr.getAddrpro())) {
                String addrproname = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerSr.getAddrpro());
                addrproname = StringUtils.isEmpty(addrproname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrpro()) : addrproname;
                prisonerSr.setAddrproname(addrproname);
            } else {
                prisonerSr.setAddrproname("");
            }
            if(!StringUtils.isEmpty(prisonerSr.getAddrcity())) {
                String addrcityname = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerSr.getAddrcity());
                addrcityname = StringUtils.isEmpty(addrcityname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrcity()) : addrcityname;
                prisonerSr.setAddrcityname(addrcityname);
            } else {
                prisonerSr.setAddrcityname("");
            }
            if(!StringUtils.isEmpty(prisonerSr.getAddrcou())) {
                String addrcouname = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerSr.getAddrcou());
                addrcouname = StringUtils.isEmpty(addrcouname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrcou()) : addrcouname;
                prisonerSr.setAddrcouname(addrcouname);
            } else {
                prisonerSr.setAddrcouname("");
            }
            if(!StringUtils.isEmpty(prisonerSr.getAddrvil())) {
                String addrvilname = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerSr.getAddrvil());
                addrvilname = StringUtils.isEmpty(addrvilname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrvil()) : addrvilname;
                prisonerSr.setAddrvilname(addrvilname);
            } else {
                prisonerSr.setAddrvilname("");
            }
            String addr = new StringBuilder(16).append(prisonerSr.getAddrproname()).append(prisonerSr.getAddrcityname())
                                               .append(prisonerSr.getAddrcouname()).append(prisonerSr.getAddrvilname())
                                               .append(prisonerSr.getAddrdetail()).toString();
            prisonerSr.setAddr(addr);
            prisaveTemp.setSrFlag(Constants.Number.NUM_ONE);
        }
        // 3.5、封装子女表
        for(PrisonerZn prisonerZn : prisonerZns) {
            prisonerZn.setId(IdGen.strid());
            prisonerZn.setAdduserid(departId);
            prisonerZn.setCreateUser(user.getAccount());
            prisonerZn.setCreateTime(date);
            prisonerZn.setUpdateUser(user.getAccount());
            prisonerZn.setUpdateTime(date);
            if(!StringUtils.isEmpty(prisonerZn.getNativepro())) {
                String nativeproName = (String)stringRedisTemplate.opsForHash()
                                                                  .get("areaCode",prisonerZn.getNativepro());
                nativeproName = StringUtils.isEmpty(nativeproName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativepro()) : nativeproName;
                prisonerZn.setNativeproName(nativeproName);
            } else {
                prisonerZn.setNativeproName("");
            }
            if(!StringUtils.isEmpty(prisonerZn.getNativecity())) {
                String nativecityName = (String)stringRedisTemplate.opsForHash()
                                                                   .get("areaCode",prisonerZn.getNativecity());
                nativecityName = StringUtils.isEmpty(nativecityName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativecity()) : nativecityName;
                prisonerZn.setNativecityName(nativecityName);
            } else {
                prisonerZn.setNativecityName("");
            }
            if(!StringUtils.isEmpty(prisonerZn.getNativecou())) {
                String nativecouName = (String)stringRedisTemplate.opsForHash()
                                                                  .get("areaCode",prisonerZn.getNativecou());
                nativecouName = StringUtils.isEmpty(nativecouName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativecou()) : nativecouName;
                prisonerZn.setNativecouName(nativecouName);
            } else {
                prisonerZn.setNativecouName("");
            }
            if(!StringUtils.isEmpty(prisonerZn.getNativevill())) {
                String nativevillName = (String)stringRedisTemplate.opsForHash()
                                                                   .get("areaCode",prisonerZn.getNativevill());
                nativevillName = StringUtils.isEmpty(nativevillName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativevill()) : nativevillName;
                prisonerZn.setNativevillName(nativevillName);
            } else {
                prisonerZn.setNativevillName("");
            }
            if(!StringUtils.isEmpty(prisonerZn.getPlacepro())) {
                String placeproName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerZn.getPlacepro());
                placeproName = StringUtils.isEmpty(placeproName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacepro()) : placeproName;
                prisonerZn.setPlaceproName(placeproName);
            } else {
                prisonerZn.setPlaceproName("");
            }
            if(!StringUtils.isEmpty(prisonerZn.getPlacecity())) {
                String placecityName = (String)stringRedisTemplate.opsForHash()
                                                                  .get("areaCode",prisonerZn.getPlacecity());
                placecityName = StringUtils.isEmpty(placecityName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacecity()) : placecityName;
                prisonerZn.setPlacecityName(placecityName);
            } else {
                prisonerZn.setPlacecityName("");
            }
            if(!StringUtils.isEmpty(prisonerZn.getPlacecou())) {
                String placecouName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerZn.getPlacecou());
                placecouName = StringUtils.isEmpty(placecouName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacecou()) : placecouName;
                prisonerZn.setPlacecouName(placecouName);
            } else {
                prisonerZn.setPlacecouName("");
            }
            if(!StringUtils.isEmpty(prisonerZn.getPlacevill())) {
                String placevillName = (String)stringRedisTemplate.opsForHash()
                                                                  .get("areaCode",prisonerZn.getPlacevill());
                placevillName = StringUtils.isEmpty(placevillName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacevill()) : placevillName;
                prisonerZn.setPlacevillName(placevillName);
            } else {
                prisonerZn.setPlacevillName("");
            }
            String hujidi = new StringBuilder(16).append(prisonerZn.getNativeproName())
                                                 .append(prisonerZn.getNativecityName())
                                                 .append(prisonerZn.getNativecouName())
                                                 .append(prisonerZn.getNativevillName())
                                                 .append(prisonerZn.getNativenum()).toString();
            prisonerZn.setHujidi(hujidi);
            String juzhudi = new StringBuilder(16).append(prisonerZn.getPlaceproName())
                                                  .append(prisonerZn.getPlacecityName())
                                                  .append(prisonerZn.getPlacecouName())
                                                  .append(prisonerZn.getPlacevillName())
                                                  .append(prisonerZn.getPlacenum()).toString();
            prisonerZn.setJuzhudi(juzhudi);
            prisaveTemp.setZzFlag(Constants.Number.NUM_ONE);
        }
        // 封装核查信息表
        {
            prisonerHc.setId(prisonerMain.getId());
            prisonerHc.setStartCheckPhone(hnAjxx.getCbrdh());
            prisonerHc.setStartCheckTel(hnAjxx.getCbrsjhm());
            prisonerHc.setStartCheckPerson(user.getUsername());
            prisonerHc.setStartCheckTime(hnAjxx.getFqhcTime());
            prisonerHc.setSpecialFlag(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setCreateUser(user.getAccount());
            prisonerHc.setCreateTime(date);
            prisonerHc.setUpdateUser(user.getAccount());
            prisonerHc.setUpdateTime(date);
            prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setFailurenum(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setSpecialFlag(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
        }
        hnInterfaceOpposite.setId(IdGen.strid());
        hnInterfaceOpposite.setCreateTime(date);
        hnInterfaceOpposite.setKbmrybh(hnMessage.getKbmrybh());
        hnInterfaceOpposite.setLcslbh(hnMessage.getLcslbh());
        hnInterfaceOpposite.setRwh(hnMessage.getRwh());
        hnInterfaceOpposite.setFsdwCode(hnMessage.getFsdwCode());
        hnInterfaceOpposite.setFsdwName(hnMessage.getFsdwName());
        hnInterfaceOpposite.setFsTime(hnMessage.getFsTime());
        hnInterfaceOpposite.setYsr(hnMessage.getYsr());
        hnInterfaceOpposite.setYsrdh(hnMessage.getYsrdh());
        hnInterfaceOpposite.setCbr(hnMessage.getCbr());
        hnInterfaceOpposite.setCbrdh(hnMessage.getCbrdh());
        hnInterfaceOpposite.setProcessType(hnMessage.getLcjdbh());
        // 设置接收状态默认为0
        hnInterfaceOpposite.setHcType(Constants.NumberStr.NUM_STR_ZERO);
        hnInterfaceOpposite.setPgType(Constants.NumberStr.NUM_STR_ZERO);
        hnInterfaceOpposite.setXjType(Constants.NumberStr.NUM_STR_ZERO);
        hnInterfaceOpposite.setFileName(hnMessage.getZipName());
        hnInterfaceOpposite.setMessageData(JsonUtil.toText(hnMessage));
        hnInterfaceOpposite.setFlag(Constants.NumberStr.NUM_STR_ZERO);
    }

    /**
     * 校验数据
     * @param param param
     * @return Result
     */
    private Result check(String param,HnMessageVo hnMessage) {
        PrisonerMain prisonerMain;
        PrisonerFx prisonerFx;
        Map<String,Object> paramMap = JsonUtil.toMap(param);
        HnAjxxVo hnAjxx;
        Date date = new Date();
        // 获取基本信息(PrisonerMain)
        Map<String,Object> prisonerMainMap;
        if(null != paramMap.get("PrisonerMain") && !"".equals(paramMap.get("PrisonerMain").toString())) {
            prisonerMainMap = JsonUtil.toMap(paramMap.get("PrisonerMain").toString());
        } else {
            prisonerMainMap = new HashMap<>(16);
        }
        // 获取服刑信息(PrisonerFx)
        if(null != paramMap.get("prisonerFx") && !"".equals(paramMap.get("prisonerFx").toString())) {
            prisonerFx = JsonUtil.toBean(paramMap.get("prisonerFx").toString(),PrisonerFx.class);
        } else {
            prisonerFx = new PrisonerFx();
        }
        // 获取社会关系信息(prisonerSr)
        List<PrisonerSr> prisonerSrs;
        if(null != paramMap.get("prisonerSr") && !"".equals(paramMap.get("prisonerSr").toString())) {
            prisonerSrs = JsonUtil.toList(paramMap.get("prisonerSr").toString(),PrisonerSr.class);
        } else {
            prisonerSrs = new ArrayList<>(16);
        }
        // 获取未成年子女信息(prisonerZn)
        List<PrisonerZn> prisonerZns;
        if(null != paramMap.get("prisonerZn") && !"".equals(paramMap.get("prisonerZn").toString())) {
            prisonerZns = JsonUtil.toList(paramMap.get("prisonerZn").toString(),PrisonerZn.class);
        } else {
            prisonerZns = new ArrayList<>(16);
        }
        // 获取发起核查信息(AJXX)
        Map<String,Object> ajxxMap;
        if(null != paramMap.get("hnAjxx") && !"".equals(paramMap.get("hnAjxx").toString())) {
            ajxxMap = JsonUtil.toMap(paramMap.get("hnAjxx").toString());
        } else {
            ajxxMap = new HashMap<>(16);
        }
        Map<String,Object> messageMap;
        if(null != paramMap.get("hnMessage") && !"".equals(paramMap.get("hnMessage").toString())) {
            messageMap = JsonUtil.toMap(paramMap.get("hnMessage").toString());
        } else {
            messageMap = new HashMap<>(16);
        }
        // 获取接口对接用户
        String fsdwCode = (String)messageMap.get("fsdwCode");
        String kbmrybh = (String)prisonerMainMap.get("kbmrybh");
        UserInterFaceEntity userLogin = userLoginDetailsMapper.getInfoByDepartId(fsdwCode);
        if(null == userLogin) {
            return Result.failure(HnStyleReturnCode.NOT_FIND_USER,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
        }
        // 校验主表(prisonerMain)
        {
            // 去除多余空格
            for(Map.Entry<String,Object> next : prisonerMainMap.entrySet()) {
                Object value = next.getValue();
                if(value instanceof String) {
                    next.setValue(((String)value).trim());
                }
            }
            // 从PrisonerMain中获取参数
            // 证件类型
            String zjlxCode = (String)prisonerMainMap.get("idType");
            // 身份证号
            String zjNo = (String)prisonerMainMap.get("idNum");
            // age
            String age = (String)prisonerMainMap.get("age");
            // 户籍类型编码
            String hjlxCode = (String)prisonerMainMap.get("priAddr");
            // 户籍地详细地址
            String hjdxxdz = (String)prisonerMainMap.get("nativenum");
            // 居住地详细地址
            String jzdxxdz = (String)prisonerMainMap.get("placenum");
            // 逮捕机构详细地址
            String dbjgxxdz = (String)prisonerMainMap.get("arrestnum");
            // 原侦查机关详细地址
            String yzcjgxxdz = (String)prisonerMainMap.get("investigateNum");
            String idType = (String) prisonerMainMap.get("idType");
            if(Constants.NumberStr.NUM_STR_NINE_NINE.equals(idType)) {
                prisonerMainMap.put("idNum","");
            }
            // 开始业务数据字段校验
            // 预安置人员 户籍地详细地址不能为空
            if(StringUtils.isBlank(hjdxxdz)) {
                return Result.failure(HnStyleReturnCode.PRISONERMAIN_HJDXXDZ_IS_NULL,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
            }
            // 封装实体类
            String json = JSON.toJSONString(prisonerMainMap);
            prisonerMain = JsonUtil.toBean(json,PrisonerMain.class);
            prisonerMain.setCreateUser(userLogin.getAccount());
            prisonerMain.setCreateTime(date);
            prisonerMain.setUpdateUser(userLogin.getAccount());
            prisonerMain.setUpdateTime(date);
            String address = getAddress(hjdxxdz);
            if(StrUtil.containsEquals(address.substring(address.length() - 1),"街道","镇","乡","民族乡","苏木","民族苏木","市辖区")) {
                Map<String,Object> allArea = dataTransmissionService.getVagueAllArea(address);
                String sheng;
                String shi;
                String xian;
                String jiedao;
                if(allArea.size() > 0) {
                    sheng = allArea.get("sheng_code").toString();
                    shi = allArea.get("dishi_code").toString();
                    xian = allArea.get("quxian_code").toString();
                    jiedao = allArea.get("jiedao_code").toString();
                    prisonerMain.setNativepro(sheng);
                    prisonerMain.setNativecity(shi);
                    prisonerMain.setNativecou(xian);
                    prisonerMain.setNativevill(jiedao);
                } else {
                    return Result.failure(HnStyleReturnCode.PRISONERMAIN_HJDXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                }
            } else {
                return Result.failure(HnStyleReturnCode.PRISONERMAIN_HJDXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
            }
            // 预安置人员 户籍地详细地址长度不能超过100
            if(StringUtils.isNotBlank(hjdxxdz) && 100 < hjdxxdz.length()) {
                return Result.failure(HnStyleReturnCode.PRISONERMAIN_HJDXXDZ_IS_NULL,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
            }
            // 校验居住地信息
            if(StringUtils.isNotBlank(jzdxxdz)) {
                String address1 = getAddress(jzdxxdz);
                if(StrUtil.containsEquals(address1.substring(address1.length() - 1),"街道","镇","乡","民族乡","苏木","民族苏木","市辖区")) {
                    Map<String,Object> allArea1 = dataTransmissionService.getVagueAllArea(address1);
                    String sheng;
                    String shi;
                    String xian;
                    String jiedao;
                    if(allArea1.size() > 0) {
                        sheng = allArea1.get("sheng_code").toString();
                        shi = allArea1.get("dishi_code").toString();
                        xian = allArea1.get("quxian_code").toString();
                        jiedao = allArea1.get("jiedao_code").toString();
                        prisonerMain.setPlacepro(sheng);
                        prisonerMain.setPlacecity(shi);
                        prisonerMain.setPlacecou(xian);
                        prisonerMain.setPlacevill(jiedao);
                    } else {
                        return Result.failure(HnStyleReturnCode.PRISONERMAIN_JZDXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                    }
                } else {
                    return Result.failure(HnStyleReturnCode.PRISONERMAIN_JZDXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                }
            }
            if(StringUtils.isNotBlank(jzdxxdz) && 100 < jzdxxdz.length()) {
                return Result.failure(HnStyleReturnCode.PRISONERMAIN_JZD_INDEX_OUT_OF_BOUNDS,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
            }
            // 湖南对接无法确认户籍类型。
            // 户籍为查不清户籍，需要校验原侦查机关地址
            // 预安置人员 原侦查机关详细地址不能为空
            if(StringUtils.isNotBlank(yzcjgxxdz)) {
                String address1 = getAddress(yzcjgxxdz);
                if(StringUtils.isNotBlank(yzcjgxxdz)) {
                    if(StrUtil.containsEquals(address1.substring(address1.length() - 1),"街道","镇","乡","民族乡","苏木","民族苏木","市辖区")) {
                        Map<String,Object> allArea1 = dataTransmissionService.getVagueAllArea(address1);
                        String sheng;
                        String shi;
                        String xian;
                        String jiedao;
                        if(allArea1.size() > 0) {
                            sheng = allArea1.get("sheng_code").toString();
                            shi = allArea1.get("dishi_code").toString();
                            xian = allArea1.get("quxian_code").toString();
                            jiedao = allArea1.get("jiedao_code").toString();
                            prisonerMain.setInvestigatePro(sheng);
                            prisonerMain.setInvestigateCity(shi);
                            prisonerMain.setInvestigateCou(xian);
                            prisonerMain.setInvestigateVill(jiedao);
                        } else {
                            return Result.failure(HnStyleReturnCode.PRISONERMAIN_YZCJGXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                        }
                    } else {
                        return Result.failure(HnStyleReturnCode.PRISONERMAIN_YZCJGXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                    }

                    if(StringUtils.isNotBlank(yzcjgxxdz) && 100 < yzcjgxxdz.length()) {
                        return Result.failure(HnStyleReturnCode.PRISONERMAIN_YZCJGXXDZ_INDEX_OUT_OF_BOUNDS,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                    }
                }
            }
            // 校验非大陆户籍 priAddr为"04","05","06","07","08" TODO cv代码,公安对接未提供户籍字典
            if(StringUtils.isNotBlank(dbjgxxdz)) {
                String address2 = getAddress(yzcjgxxdz);
                // 判断逮捕机关是否为(县、自治县、旗、自治旗、市（县级）、市辖区、林区、特区结尾)直接返回
                if(StrUtil.containsEquals(address2.substring(address2.length() - 1),"街道","镇","乡","民族乡","苏木","民族苏木","市辖区")) {
                    Map<String,Object> allArea1 = dataTransmissionService.getVagueAllArea(address2);
                    String sheng;
                    String shi;
                    String xian;
                    String jiedao;
                    if(allArea1.size() > 0) {
                        sheng = allArea1.get("sheng_code").toString();
                        shi = allArea1.get("dishi_code").toString();
                        xian = allArea1.get("quxian_code").toString();
                        jiedao = allArea1.get("jiedao_code").toString();
                        prisonerMain.setArrestpro(sheng);
                        prisonerMain.setArrestcity(shi);
                        prisonerMain.setArrestcou(xian);
                        prisonerMain.setArrestvill(jiedao);
                    } else {
                        return Result.failure(HnStyleReturnCode.PRISONERMAIN_DBJGXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                    }
                } else {
                    return Result.failure(HnStyleReturnCode.PRISONERMAIN_DBJGXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                }
            }
            if(StringUtils.isNotBlank(dbjgxxdz) && 100 < dbjgxxdz.length()) {
                return Result.failure(HnStyleReturnCode.PRISONERMAIN_DBJGXXDZ_INDEX_OUT_OF_BOUNDS,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
            }
            // 如果证件类型为身份证，生日是空，默认设置生日为省份证中出生日期
            if(Constants.NumberStr.NUM_STR_ONE.equals(zjlxCode) && !StringUtils.isEmpty(zjNo) && 18 == zjNo.length() && StringUtils.isEmpty(age)) {
                // 身份证不为空，并且为18位身份证，设置生日为身份证的7～14位
                String year = zjNo.substring(6,10);
                String month = zjNo.substring(10,12);
                String day = zjNo.substring(12,14);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date birthday = null;
                try {
                    // 注意格式需要与上面一致，不然会出现异常
                    birthday = sdf.parse(new StringBuffer(year).append("-").append(month).append("-").append(day)
                                                               .toString());
                } catch(ParseException e) {
                    log.error("发生异常:",e);
                }
                prisonerMain.setAge(birthday);
            }
            // 城镇、农村
            if(StringUtils.isNotBlank(hjdxxdz)) {
                prisonerMain.setHjType(Constants.NumberStr.NUM_STR_ZERO_ONE);
                prisonerMain.setPriAddr(Constants.NumberStr.NUM_STR_ZERO_ONE);
                prisonerMain.setDetailType("");
                prisonerMain.setArrestpro("");
                prisonerMain.setArrestcity("");
                prisonerMain.setArrestcou("");
                prisonerMain.setArrestvill("");
                prisonerMain.setArrestnum("");
                prisonerMain.setInvestigatePro("");
                prisonerMain.setInvestigateCity("");
                prisonerMain.setInvestigateCou("");
                prisonerMain.setInvestigateVill("");
                prisonerMain.setInvestigateNum("");
            } else if(StringUtils.isNotBlank(dbjgxxdz)) {
                // 查不清，设置原侦查机关
                prisonerMain.setPriAddr(Constants.NumberStr.NUM_STR_ZERO_ONE);
                prisonerMain.setHjType(Constants.NumberStr.NUM_STR_ZERO_TWO);
                prisonerMain.setDetailType("");
                prisonerMain.setInvestigateNum(yzcjgxxdz);
                prisonerMain.setNativepro("");
                prisonerMain.setNativecity("");
                prisonerMain.setNativecou("");
                prisonerMain.setNativevill("");
                prisonerMain.setNativenum("");
                prisonerMain.setPlacepro("");
                prisonerMain.setPlacecity("");
                prisonerMain.setPlacecou("");
                prisonerMain.setPlacevill("");
                prisonerMain.setPlacenum("");
                prisonerMain.setArrestpro("");
                prisonerMain.setArrestcity("");
                prisonerMain.setArrestcou("");
                prisonerMain.setArrestvill("");
                prisonerMain.setArrestnum("");
            } else {
                // 非大陆，设置逮捕机关地址
                prisonerMain.setPriAddr(Constants.NumberStr.NUM_STR_ZERO_FOUR);
                prisonerMain.setHjType(Constants.NumberStr.NUM_STR_ZERO_ONE);
                String detailType = "";
                if(Constants.NumberStr.NUM_STR_ZERO_FOUR.equals(hjlxCode)) {
                    detailType = Constants.NumberStr.NUM_STR_ONE;
                } else if(Constants.NumberStr.NUM_STR_ZERO_FIVE.equals(hjlxCode)) {
                    detailType = Constants.NumberStr.NUM_STR_TWO;
                } else if(Constants.NumberStr.NUM_STR_ZERO_SIX.equals(hjlxCode)) {
                    detailType = Constants.NumberStr.NUM_STR_THREE;
                } else if(Constants.NumberStr.NUM_STR_ZERO_SEVEN.equals(hjlxCode)) {
                    detailType = Constants.NumberStr.NUM_STR_FOUR;
                } else if(Constants.NumberStr.NUM_STR_ZERO_EIGHT.equals(hjlxCode)) {
                    detailType = Constants.NumberStr.NUM_STR_FIVE;
                }
                prisonerMain.setDetailType(detailType);
                prisonerMain.setArrestnum(dbjgxxdz);
                prisonerMain.setNativepro("");
                prisonerMain.setNativecity("");
                prisonerMain.setNativecou("");
                prisonerMain.setNativevill("");
                prisonerMain.setNativenum("");
                prisonerMain.setPlacepro("");
                prisonerMain.setPlacecity("");
                prisonerMain.setPlacecou("");
                prisonerMain.setPlacevill("");
                prisonerMain.setPlacenum("");
                prisonerMain.setInvestigatePro("");
                prisonerMain.setInvestigateCity("");
                prisonerMain.setInvestigateCou("");
                prisonerMain.setInvestigateVill("");
                prisonerMain.setInvestigateNum("");
            }
        }
        // 校验社会关系信息
        {
            String sheng;
            String shi;
            String xian;
            String jiedao;
            for(PrisonerSr prisonerSr : prisonerSrs) {
                prisonerSr.setCreateUser(userLogin.getAccount());
                prisonerSr.setCreateTime(date);
                prisonerSr.setUpdateUser(userLogin.getAccount());
                prisonerSr.setUpdateTime(date);
                // 家庭住址省详细
                String jtzxxx = prisonerSr.getAddrdetail();
                if(!StringUtils.isEmpty(jtzxxx)) {
                    String address = getAddress(jtzxxx);
                    if(StrUtil.containsEquals(address.substring(address.length() - 1),"街道","镇","乡","民族乡","苏木","民族苏木","市辖区")) {
                        Map<String,Object> allArea1 = dataTransmissionService.getVagueAllArea(address);
                        if(allArea1.size() > 0) {
                            sheng = allArea1.get("sheng_code").toString();
                            shi = allArea1.get("dishi_code").toString();
                            xian = allArea1.get("quxian_code").toString();
                            jiedao = allArea1.get("jiedao_code").toString();
                            prisonerSr.setAddrpro(sheng);
                            prisonerSr.setAddrcity(shi);
                            prisonerSr.setAddrcou(xian);
                            prisonerSr.setAddrvil(jiedao);
                        } else {
                            return Result.failure(HnStyleReturnCode.PRISONERMAIN_JZDXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                        }
                    } else {
                        return Result.failure(HnStyleReturnCode.PRISONERMAIN_JZDXXDZ_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                    }
                }
                if(StringUtils.isNotBlank(jtzxxx) && 100 < jtzxxx.length()) {
                    return Result.failure(HnStyleReturnCode.PRISONERSR_JTZXXX_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                }
            }
        }
        // 未成年子女信息(PrisonerZn)
        {
            String sheng;
            String shi;
            String xian;
            String jiedao;
            for(PrisonerZn prisonerZn : prisonerZns) {
                prisonerZn.setCreateUser(userLogin.getAccount());
                prisonerZn.setCreateTime(date);
                prisonerZn.setUpdateUser(userLogin.getAccount());
                prisonerZn.setUpdateTime(date);
                // 户籍地详细地址
                String nativenum = prisonerZn.getNativenum();
                String placenum = prisonerZn.getPlacenum();
                if(!StringUtils.isEmpty(nativenum)) {
                    String address = getAddress(nativenum);
                    if(StrUtil.containsEquals(address.substring(address.length() - 1),"街道","镇","乡","民族乡","苏木","民族苏木","市辖区")) {
                        Map<String,Object> allArea1 = dataTransmissionService.getVagueAllArea(address);
                        if(allArea1.size() > Constants.Number.NUM_ZERO) {
                            sheng = allArea1.get("sheng_code").toString();
                            shi = allArea1.get("dishi_code").toString();
                            xian = allArea1.get("quxian_code").toString();
                            jiedao = allArea1.get("jiedao_code").toString();
                            prisonerZn.setNativepro(sheng);
                            prisonerZn.setNativecity(shi);
                            prisonerZn.setNativecou(xian);
                            prisonerZn.setNativevill(jiedao);
                        } else {
                            return Result.failure(HnStyleReturnCode.PRISONERZN_HJDXXXX_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                        }
                    } else {
                        return Result.failure(HnStyleReturnCode.PRISONERZN_HJDXXXX_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                    }
                }
                if(!StringUtils.isEmpty(placenum)) {
                    String address = getAddress(placenum);
                    if(StrUtil.containsEquals(address.substring(address.length() - 1),"街道","镇","乡","民族乡","苏木","民族苏木","市辖区")) {
                        Map<String,Object> allArea1 = dataTransmissionService.getVagueAllArea(address);
                        if(allArea1.size() > 0) {
                            sheng = allArea1.get("sheng_code").toString();
                            shi = allArea1.get("dishi_code").toString();
                            xian = allArea1.get("quxian_code").toString();
                            jiedao = allArea1.get("jiedao_code").toString();
                            prisonerZn.setPlacepro(sheng);
                            prisonerZn.setPlacecity(shi);
                            prisonerZn.setPlacecou(xian);
                            prisonerZn.setPlacevill(jiedao);
                        } else {
                            return Result.failure(HnStyleReturnCode.PRISONERZN_JZDXXXX_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                        }
                    }else {
                        return Result.failure(HnStyleReturnCode.PRISONERZN_JZDXXXX_IS_ERROR,getResultMap(hnMessage,Constants.NumberStr.NUM_STR_TWO));
                    }
                }
            }
        }
        // 校验核查信息
        {
            for(Map.Entry<String,Object> next : ajxxMap.entrySet()) {
                Object value = next.getValue();
                if(value instanceof String) {
                    next.setValue(((String)value).trim());
                }
            }
            // 封装实体类
            String json = JSON.toJSONString(ajxxMap);
            hnAjxx = JsonUtil.toBean(json,HnAjxxVo.class);
        }
        // 校验MESSAGE信息
        {
            for(Map.Entry<String,Object> next : messageMap.entrySet()) {
                Object value = next.getValue();
                if(value instanceof String) {
                    next.setValue(((String)value).trim());
                }
            }
            // 封装实体类
            String json = JSON.toJSONString(messageMap);
            hnMessage = JsonUtil.toBean(json,HnMessageVo.class);
            hnMessage.setKbmrybh(kbmrybh);
        }
        ArrayList<Object> resultList = new ArrayList<>();
        resultList.add(prisonerMain);
        resultList.add(prisonerFx);
        resultList.add(prisonerSrs);
        resultList.add(prisonerZns);
        resultList.add(hnAjxx);
        resultList.add(hnMessage);
        return Result.success(resultList);
    }

    /**
     * 基本信息,服刑信息,社会关系,未成年子女信息,核查信息
     * @param priNum 服刑人员编号
     * @return HashMap<String,Object>
     */
    private HashMap<String,Object> getVerificationInfo(String priNum) {
        HashMap<String,Object> resultMap = new HashMap<>(16);
        PrisonerMain prisonerMain = prisonerMainMapper.selectPrisonerMain(priNum);
        PrisonerFx prisonerFx = prisonerFxMapper.selectById(priNum);
        List<PrisonerSr> prisonerSrs = prisonerSrMapper.getListByPrinum(priNum);
        List<PrisonerZn> prisonerZns = prisonerZnMapper.getListByPriNum(priNum);
        PrisonerHc prisonerHc = verificationMapper.selectHcByPriNum(priNum);
        resultMap.put("prisonerMain",prisonerMain);
        resultMap.put("prisonerFx",prisonerFx);
        resultMap.put("prisonerSrs",prisonerSrs);
        resultMap.put("prisonerZns",prisonerZns);
        resultMap.put("prisonerHc",prisonerHc);
        return resultMap;
    }

    /**
     * 职业技能信息,减刑假释信息,出监评估信息
     * @param priNum 服刑人员编号
     * @return HashMap<String,Object>
     */
    private HashMap<String,Object> getBridgingInfo(String priNum) {
        HashMap<String,Object> resultMap = new HashMap<>(16);
        List<PrisonerJxjs> prisonerJxjs = xxblMapper.selectJxjsByPriNum(priNum);
        PrisonerCjpg prisonerCjpg = prisonerFxMapper.selectCjpgInfoByPrNum(priNum);
        resultMap.put("prisonerJxjs",prisonerJxjs);
        resultMap.put("prisonerCjpg",prisonerCjpg);
        return resultMap;
    }

    /**
     * 获取住址信息
     * @param address 住址
     * @return String
     */
    private String getAddress(String address) {
        String[] str1 = address.split("街道");
        String[] str2 = str1[0].split("镇");
        String[] str3 = str2[0].split("乡");
        String[] str4 = str3[0].split("民族乡");
        String[] str5 = str4[0].split("苏木");
        String[] str6 = str5[0].split("民族苏木");
        String[] str7 = str6[0].split("市辖区");
        return str7[0];
    }
}